package springcloud.learning.oauth2.server.servicee;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import springcloud.learning.oauth2.server.pojo.User;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/5/27 11:04
 **/
@Service
public class UserService implements UserDetailsService {

    private List<User> userList;

    @Autowired
    PasswordEncoder passwordEncoder;

    @PostConstruct
    public void initData() {
        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new User("admin", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
        userList.add(new User("user1", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
        userList.add(new User("user2", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
    }

    /**
     * 通过用户名获取用户信息
     * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = userList.stream().filter(u -> u.getUsername().equals(username)).findFirst();
        return user.orElseThrow(() -> new UsernameNotFoundException("用户名或密码错误！"));
    }
}
